import { Form, Input, Modal, Select, SelectProps, Upload, UploadFile } from 'antd'
import { CreatePictureParmas } from '../../../api/picture'
import { useAppSelector } from '../../../hooks/store'
import { uploadFiles } from '../../../api/upload'
import { RcFile, UploadProps } from 'antd/es/upload'
import { useState } from 'react'
import { PlusOutlined } from '@ant-design/icons'
interface PictureFormModalProps<T> {
    name: string;
    open: boolean;
    title: string;
    onOK: (values: T) => void;
    onCancel: () => void;
    okText?: string;
    initialValues?: Partial<T>
}
const getBase64 = (file: RcFile): Promise<string> =>
    new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = () => resolve(reader.result as string)
        reader.onerror = (error) => reject(error)
    })
const PictureFormModal = <T extends CreatePictureParmas>({
    name,
    open,
    onOK: onCreate,
    onCancel,
    title,
    okText = '确认',
    initialValues
}: PictureFormModalProps<T>): JSX.Element => {
    const [form] = Form.useForm<T>()
    const categoryState = useAppSelector((state) => state.category)

    const selectOptions: SelectProps['options'] = categoryState.list.map((c) => ({
        label: c.name,
        value: c.id
    }))
    const [previewOpen, setPreviewOpen] = useState(false)
    const [previewImage, setPreviewImage] = useState('')
    const [previewTitle, setPreviewTitle] = useState('')
    const [fileList, setFileList] = useState<UploadFile[]>([])
    const handleCancel = () => setPreviewOpen(false)

    const uploadButton = (
        <div>
          <PlusOutlined />
          <div style={{ marginTop: 8 }}>Upload</div>
        </div>
      )

    // 图片点击放大查看
    const handlePreview = async (file: UploadFile) => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj as RcFile)
        }

        setPreviewImage(file.url || (file.preview as string))
        setPreviewOpen(true)
        setPreviewTitle(file.name || file.url!.substring(file.url!.lastIndexOf('/') + 1))
    }
    // base64转Blob
    // const base64ToBlob = (code: string) => {
    //     const parts = code.split(';base64,')
    //     const contentType = parts[0].split(':')[1]
    //     const raw = window.atob(parts[1])
    //     const rawLength = raw.length
    //     const uInt8Array = new Uint8Array(rawLength)
    //     for (let i = 0; i < rawLength; ++i) {
    //         uInt8Array[i] = raw.charCodeAt(i)
    //     }
    //     return new Blob([uInt8Array], { type: contentType })
    // }

    const handleChange: UploadProps['onChange'] = ({ fileList: newFileList }) =>
    setFileList(newFileList)

    // 自定义上传逻辑
    const customRequest: UploadProps['customRequest'] = async (options) => {
        const file = options.file as RcFile
        // uploadFunc 是服务器上传操作
        const formData = new FormData()
        formData.append('file', file)
        try {
            const res = await uploadFiles(formData)
            if (options.onSuccess) {
                options.onSuccess(res)
            }

        } catch (error) {
            //
        }
    }

    return (
        <>
            <Modal
                centered
                width={700}
                // 注意 : 这儿3.x展示modal属性是visible,5.x是open
                open={previewOpen}
                title={previewTitle}
                footer={null}
                onCancel={handleCancel}
            >
                <img
                    alt="example"
                    style={{
                        width: '100%',
                    }}
                    src={previewImage}
                />
            </Modal>
            <Modal
                destroyOnClose={true}
                open={open}
                title={title}
                okText={okText}
                cancelText='取消'
                onCancel={onCancel}

                onOk={() => {
                    form
                        .validateFields()
                        .then((values: T) => {
                            form.resetFields()
                            onCreate(values)
                        })
                        .catch((info: unknown) => {
                            console.log('Validate Failed:', info)
                        })
                }}
            >
                <Form
                    form={form}
                    layout="vertical"
                    name={name}
                    initialValues={initialValues}
                >
                    <Form.Item
                        label="imageUrl"
                        name='imageUrl'
                        extra="支持上传png,jpg"
                        getValueFromEvent={(event: { fileList: UploadFile<unknown>[] }) => {
                            const fileList = event.fileList as UploadFile[]
                            console.log('getValueFromEvent',event)

                            return fileList[0]?.response?.accessUrl
                        }}
                    >
                        <Upload
                            listType="picture-card"
                            fileList={fileList}
                            onPreview={handlePreview}
                            onChange={handleChange}
                            customRequest={customRequest}
                        >
                            {fileList.length >= 1 ? null : uploadButton}
                        </Upload>
                    </Form.Item>
                    <Form.Item
                        name="title"
                        label="标题"
                        rules={[{ required: true, message: 'Please input the title of collection!' }]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        name="desc"
                        label="简介"
                        rules={[{ required: true, message: 'Please input the Description of collection!' }]}
                    >
                        <Input type="textarea" />
                    </Form.Item>
                    <Form.Item
                        name="categoryId"
                        label='文件夹'
                    >
                        <Select
                            options={selectOptions}
                        />
                    </Form.Item>
                </Form>
            </Modal>
        </>

    )
}

export default PictureFormModal